package com.qianfeng.controller.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.dto.R;
import com.qianfeng.exception.MyBaseException;
import com.qianfeng.status.ResultCode;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/*
 *@Description:自定义异常增强通知类
 *@author:刘哥
 *@Date:86180 2022/9/5 20:13
 */
@RestControllerAdvice//异常通知增强类注解
public class MyControllerAdvice {
    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @ExceptionHandler(MyBaseException.class)
    public R processBaseException(MyBaseException exception){
        exception.printStackTrace();//打印异常信息
        return R.getResult(exception.getCode(),exception.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public R processBaseException(Exception exception){
        exception.printStackTrace();
        return R.getResult(ResultCode.FAIL, "网络异常,请检查网络");
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R processMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        String defaultMessage = exception.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        try {
            Map map = objectMapper.readValue(defaultMessage, Map.class);
            return R.getResult((Integer) map.get("code"), (String) map.get("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ERROR();
    }
}
